package edu.osumc.bmi.restful.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import edu.osumc.bmi.restful.schema.User;
import edu.osumc.bmi.restful.util.RestfulException;

@Component("restfulService")
public class RestfulServiceImpl implements RestfulService {

	private Map<Integer, User> dataSource;

	public RestfulServiceImpl() {
		dataSource = new HashMap<Integer, User>();
		putUser(1, "kbrant", "Kobe", "Bryant");
		putUser(2, "tmac", "Tracy", "Mac");
		putUser(3, "aiverson", "Allen", "Iverson");
	}

	public void addUser(User user) throws RestfulException {
		if (idExists(user.getId())) {
			throw new RestfulException("Cannot add user. Id already exists.");
		}
		dataSource.put(user.getId(), user);
	}

	public void deleteUser(Integer id) throws RestfulException {
		if (!idExists(id)) {
			throw new RestfulException(
					"Cannot delete user. Id does not exists.");
		}
		dataSource.remove(id);
	}

	public List<User> getAllUsers() {
		List<User> results = new ArrayList<User>(dataSource.values());
		return results;
	}

	public User getUser(Integer id) throws RestfulException {
		if (!idExists(id)) {
			throw new RestfulException("Cannot get user. ID does not exist.");
		}
		return dataSource.get(id);
	}

	public void updateUser(User user) throws RestfulException {
		if (!idExists(user.getId())) {
			throw new RestfulException("Cannot update user. ID does not exist.");
		}
		dataSource.put(user.getId(), user);
	}

	private void putUser(Integer id, String loginId, String firstName,
			String lastName) {
		User user = new User();
		user.setId(id);
		user.setLoginId(loginId);
		user.setFirstName(firstName);
		user.setLastName(lastName);
		dataSource.put(id, user);
	}

	private boolean idExists(Integer id) {
		return dataSource.containsKey(id);
	}
}
